/**
 * @Author: colpu
 * @Date: 2023-11-06 13:55:06
 * @LastEditors: colpu ycg520520@qq.com
 * @LastEditTime: 2025-04-03 22:20:22
 * @
 * @Copyright (c) 2025 by colpu, All Rights Reserved.
 */
import inquirer from "inquirer";

import spinnerFactory from "ora";
const spinner = spinnerFactory(); // 终端旋转器，loading颜色变化
import chalk from "chalk"; // 终端字符串样式模块
import shell from "shelljs"; // 脚本执行
const CWD = process.cwd();

/**
 * @function commond 执行命令方法
 * @param {String} env 环境变量
 * @param {String} argv bash 参数
 * @description 用于克隆初始化项目（ 待完成）
 */
import fs from "fs";
import { loadFile, readJSONSync } from "../utils/index.js";

function defaultConfig(data) {
  const DEFAULT = {
    name: "example",
    version: "1.0.0",
    description: "您什么都没留下~",
    license: "ISC",
    port: 3000,
  };
  for (let key in data) {
    if (!data[key]) {
      delete data[key];
    }
  }
  return Object.assign(DEFAULT, data);
}
const promptList = [
  {
    type: "input",
    message: "请输入项目名称:",
    suffix: "***推荐使用英文和下划线进行命名***",
    name: "name",
  },
  {
    type: "input",
    message: "版本:",
    name: "version",
  },
  {
    type: "input",
    message: "描述:",
    name: "description",
  },
  {
    type: "input",
    message: "仓库地址:",
    name: "repository",
  },
  {
    type: "input",
    message: "作者:",
    name: "author",
  },
  {
    type: "input",
    message: "许可协议",
    name: "license",
  },
  {
    type: "input",
    message: "端口",
    name: "port",
  },
];
export default async function init(env, argv) {
  const branchs = ["master", "api"];
  const answers = await inquirer.prompt(promptList);
  const answersConfig = defaultConfig(answers);
  const repo = "https://gitee.com/ycg520520/colpu-example.git"; // git仓库地址
  if (!shell.which("git")) {
    // 在控制台输出内容
    shell.echo("抱歉没有安装git");
    shell.exit(1);
  } else {
    let branch = argv.split(" ")[1];
    branch = branchs.indexOf(branch) > -1 ? branch : "";
    const clone = `git clone ${branch ? `-b ${branch} ` : ""}${repo} ${
      answersConfig.name
    }`;
    spinner.start(`正在下载项目 (${clone})...`);
    shell.exec(clone, async (code, stdout, stderr) => {
      debugger;
      if (code == 0) {
        spinner.succeed(chalk.green("模板克隆成功^_^。"));
        // 初始化项目
        spinner.info(chalk.green(`正在初始化项目: ${answersConfig.name}`));
        const projectDir = `${CWD}/${answersConfig.name}/`;
        const packagePath = `${projectDir}package.json`;
        const configPath = `${projectDir}src/config/index.js`;
        const pkg = await readJSONSync(packagePath);
        const config = await loadFile(configPath);
        Object.assign(pkg, answersConfig);
        pkg.repository.url = config.repository;
        config.port = config.port;
        fs.writeFileSync(packagePath, JSON.stringify(pkg, null, "\t"));
        let configStr = `export default `;
        configStr += JSON.stringify(config, null, "\t");
        configStr = configStr.replace(/"([a-zA-Z0-9_]+)":/gi, "$1:");
        fs.writeFileSync(configPath, configStr);
        spinner.succeed(chalk.green(`初始化项目 ${answersConfig.name} 成功`));
        spinner.stop();
      } else {
        console.error(stderr);
        process.exit();
      }
    });
  }
}
